package com.zhuiyun.project.api.system.role.controller;


import com.zhuiyun.project.annotation.OptLog;
import com.zhuiyun.project.api.system.login.service.impl.SysPermissionService;
import com.zhuiyun.project.api.system.role.entity.SysRole;
import com.zhuiyun.project.api.system.role.service.SysRoleService;
import com.zhuiyun.project.api.system.user.entity.SysUser;
import com.zhuiyun.project.api.system.user.entity.SysUserRole;
import com.zhuiyun.project.api.system.user.service.SysUserService;
import com.zhuiyun.project.common.controller.BaseController;
import com.zhuiyun.project.common.errorCode.EmErrorCode;
import com.zhuiyun.project.common.response.CommonResult;
import com.zhuiyun.project.utils.constants.CommonConstants;
import com.zhuiyun.project.utils.pageUtil.PageRequest;
import io.swagger.annotations.ApiOperation;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.*;

/**
 * 角色信息
 * 
 * @author ruoyi
 */
@RestController
@RequestMapping("/system/role")
public class SysRoleController extends BaseController
{
    @Autowired
    private SysRoleService roleService;

//    @Autowired
//    private TokenService tokenService;

    @Autowired
    private SysPermissionService permissionService;

    @Autowired
    private SysUserService userService;

//    @Autowired
//    private SysDeptService deptService;

    /**
    * @Author hbx
    * @Description 角色详情分页查询
    * @Date 2023/6/22 9:35
    * @param pageRequest
    * @param sysRole
    */
    @PreAuthorize("@ss.hasPermi('system:role:list')")
    @ApiOperation(value = "角色详情分页查询")
    @OptLog(modular = "角色详情管理", type = CommonConstants.SELECT, describe = "角色详情分页查询 ")
    @GetMapping("/list")
    public CommonResult list(PageRequest pageRequest, SysRole sysRole) {
        return CommonResult.ok(roleService.selectRoleList(pageRequest,sysRole));
    }


    /**
    * @Author hbx
    * @Description 根据角色编号获取详细信息
    * @Date 2023/6/22 9:36
    * @param roleId
    */
    @PreAuthorize("@ss.hasPermi('system:role:query')")
    @ApiOperation(value = "根据角色编号获取信息")
    @OptLog(modular = "角色详情管理", type = CommonConstants.SELECT , describe = "根据角色编号获取信息")
    @GetMapping(value = "/{roleId}")
    public CommonResult getInfo(@PathVariable Long roleId)
    {
        roleService.checkRoleDataScope(roleId);
        return CommonResult.ok(roleService.selectRoleById(roleId));
    }

    /**
    * @Author hbx
    * @Description 新增角色
    * @Date 2023/6/22 9:41
    * @param role
    */
    @PreAuthorize("@ss.hasPermi('system:role:add')")
    @ApiOperation(value = "新增角色信息")
    @OptLog(modular = "角色详情管理", type = CommonConstants.ADD, describe = "新增角色信息")
    @PostMapping
    public CommonResult add(@Validated @RequestBody SysRole role)
    {
        if (!roleService.checkRoleNameUnique(role))
        {
            return CommonResult.error("新增角色'" + role.getRoleName() + "'失败，角色名称已存在");
        }
        else if (!roleService.checkRoleKeyUnique(role))
        {
            return CommonResult.error("新增角色'" + role.getRoleName() + "'失败，角色权限已存在");
        }
//        role.setCreateBy(());
        return CommonResult.ok(roleService.insertRole(role));

    }

   /**
   * @Author hbx
   * @Description 修改保存角色
   * @Date 2023/6/22 9:41
   * @param role
   */
    @PreAuthorize("@ss.hasPermi('system:role:edit')")
    @ApiOperation(value = "修改角色信息")
    @OptLog(modular = "角色详情管理", type = CommonConstants.UPDATE,describe = "修改角色信息")
    @PutMapping
    public CommonResult edit(@Validated @RequestBody SysRole role)
    {
        roleService.checkRoleAllowed(role);
        roleService.checkRoleDataScope(role.getRoleId());
        if (!roleService.checkRoleNameUnique(role))
        {
            return CommonResult.error("修改角色'" + role.getRoleName() + "'失败，角色名称已存在");
        }
        else if (!roleService.checkRoleKeyUnique(role))
        {
            return CommonResult.error("修改角色'" + role.getRoleName() + "'失败，角色权限已存在");
        }
//        role.setUpdateBy(getUsername());
        
        if (roleService.updateRole(role) > 0)
        {
            // 更新缓存用户权限
//            LoginUser loginUser = getLoginUser();
//            if (StringUtils.isNotNull(loginUser.getUser()) && !loginUser.getUser().isAdmin())
//            {
//                loginUser.setPermissions(permissionService.getMenuPermission(loginUser.getUser()));
//                loginUser.setUser(userService.selectUserByUserName(loginUser.getUser().getUserName()));
//                tokenService.setLoginUser(loginUser);
//            }
            return CommonResult.ok(EmErrorCode.UPDATE_OK);
        }
        return CommonResult.error("修改角色'" + role.getRoleName() + "'失败，请联系管理员");
    }


    /**
    * @Author hbx
    * @Description 状态修改
    * @Date 2023/6/22 9:42
    * @param role
    */
    @PreAuthorize("@ss.hasPermi('system:role:edit')")
    @ApiOperation(value = "修改角色状态")
    @OptLog(modular = "角色详情管理" , type = CommonConstants.UPDATE, describe = "修改角色状态")
    @PutMapping("/changeStatus")
    public CommonResult changeStatus(@RequestBody SysRole role)
    {
        roleService.checkRoleAllowed(role);
        roleService.checkRoleDataScope(role.getRoleId());
//        role.setUpdateBy(getUsername());
        return CommonResult.ok(roleService.updateRoleStatus(role));
    }

    /**
    * @Author hbx
    * @Description 删除角色
    * @Date 2023/6/22 9:44
    * @param roleIds
    */
    @PreAuthorize("@ss.hasPermi('system:role:remove')")
    @ApiOperation(value = "删除角色信息")
    @OptLog(modular = "角色详情管理", type = CommonConstants.DELETE ,describe = "删除角色信息")
    @DeleteMapping("/{roleIds}")
    public CommonResult remove(@PathVariable Long[] roleIds) {
        return roleService.deleteRoleByIds(roleIds);
    }

    /**
    * @Author hbx
    * @Description 获取角色选择框列表
    * @Date 2023/6/22 9:49

    */
    @PreAuthorize("@ss.hasPermi('system:role:query')")
    @ApiOperation(value = "角色详情选择列表")
    @OptLog(modular = "角色详情管理" , type = CommonConstants.SELECT , describe = "角色详情选择列表")
    @GetMapping("/optionselect")
    public CommonResult optionselect() {
        return CommonResult.ok(roleService.selectRoleAll());
    }

    /**
    * @Author hbx
    * @Description 查询已分配用户角色列表
    * @Date 2023/6/22 9:51
    * @param pageRequest
    * @param user
    */
    @PreAuthorize("@ss.hasPermi('system:role:list')")
    @ApiOperation(value = "查询已分配用户角色列表")
    @OptLog(modular = "角色详情管理" , type = CommonConstants.SELECT ,describe = "查询已分配用户角色")
    @GetMapping("/authUser/allocatedList")
    public CommonResult allocatedList(PageRequest pageRequest,SysUser user)
    {
        return CommonResult.ok(userService.selectAllocatedList(pageRequest,user));
    }

    /**
    * @Author hbx
    * @Description 查询未分配用户角色列表
    * @Date 2023/6/22 9:53
    * @param pageRequest
    * @param user
    */
    @PreAuthorize("@ss.hasPermi('system:role:list')")
    @ApiOperation(value = "查询未分配用户角色列表")
    @OptLog(modular = "角色详情管理", type = CommonConstants.SELECT ,describe = "查询未分配用户角色")
    @GetMapping("/authUser/unallocatedList")
    public CommonResult unallocatedList(PageRequest pageRequest,SysUser user)
    {
        return CommonResult.ok(userService.selectUnallocatedList(pageRequest,user));
    }

    /**
    * @Author hbx
    * @Description 取消授权用户
    * @Date 2023/6/22 9:54
    * @param userRole
    */
    @PreAuthorize("@ss.hasPermi('system:role:edit')")
    @ApiOperation(value = "取消授权用户")
    @OptLog(modular = "角色详情管理", type = CommonConstants.UPDATE , describe = "取消授权用户")
    @PutMapping("/authUser/cancel")
    public CommonResult cancelAuthUser(@RequestBody SysUserRole userRole)
    {
        return CommonResult.ok(roleService.deleteAuthUser(userRole));
    }

    /**
    * @Author hbx
    * @Description 批量取消授权用户
    * @Date 2023/6/22 9:55
    * @param roleId
    * @param userIds
    */
    @PreAuthorize("@ss.hasPermi('system:role:edit')")
    @ApiOperation(value = "批量取消授权用户")
    @OptLog(modular = "角色详情管理", type = CommonConstants.UPDATE ,describe = "批量取消授权用户")
    @PutMapping("/authUser/cancelAll")
    public CommonResult cancelAuthUserAll(Long roleId, Long[] userIds)
    {
        return CommonResult.ok(roleService.deleteAuthUsers(roleId, userIds));
    }

    /**
    * @Author hbx
    * @Description 批量选择用户授权
    * @Date 2023/6/22 9:57
    * @param roleId
    * @param userIds
    */
    @PreAuthorize("@ss.hasPermi('system:role:edit')")
    @ApiOperation(value = "批量选择用户授权")
    @OptLog(modular = "角色详情管理", type = CommonConstants.ADD ,describe = "批量选择用户授权")
    @PutMapping("/authUser/selectAll")
    public CommonResult selectAuthUserAll(Long roleId, Long[] userIds)
    {
        roleService.checkRoleDataScope(roleId);
        return CommonResult.ok(roleService.insertAuthUsers(roleId, userIds));
    }




}
